package com.bootcamp.ex1125.exception.handler;

import com.bootcamp.ex1125.bean.BaseRespVO;
import com.bootcamp.ex1125.exception.InvalidNameException;
import com.bootcamp.ex1125.exception.LoginException;
import com.bootcamp.ex1125.exception.ParamException;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: springboot
 * @description:
 * @author: Keyu Li
 * @create: 2021-11-25 19:44
 **/

@ControllerAdvice
public class UserExceptionHandler {

    @Autowired
    HttpServletResponse resp;

    /* 参数异常，则返回就是jsp视图 */
    @ExceptionHandler(ParamException.class)
    public void userNameException(Exception ex){
        // 返回 jsp文件则参数无法正常传递，因此直接 req输出试试？
        try {
            resp.getWriter().println("<h2>"+ex.getMessage()+"<h2>");
        } catch (IOException e) {
            e.printStackTrace();
        }
//        req.setAttribute("exception",ex.getMessage());
//        return "exception";
    }

    /* 未登录hello异常，username异常，则返回 json*/
    @ResponseBody
    @ExceptionHandler({InvalidNameException.class, LoginException.class})
    public BaseRespVO userException2(Exception ex){
        return BaseRespVO.error(ex.getMessage());
    }

}
